package com.yaorange.web;


import com.github.pagehelper.PageInfo;
import com.yaorange.entity.Dept;
import com.yaorange.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("/system/dept")
public class DeptController {

    @Resource
    private DeptService deptService;


    //包含模糊查询的分页
    @GetMapping({"/page/{pageNum}/{pageSize}/{conditionDeptName}","/page/{pageNum}/{pageSize}"})
    @ResponseBody//将后台数据转成json给前端用
    public PageInfo<Dept> getPages(@PathVariable Integer pageNum, @PathVariable Integer pageSize,
                                   @PathVariable(required = false) String conditionDeptName){
        PageInfo<Dept> deptPageInfo=deptService.getPageByCondition(pageNum,pageSize,conditionDeptName);
        return deptPageInfo;
    }




    //新增部门
    @PostMapping("/addDept")
    @ResponseBody
    public Map<String,Object>addDept(@RequestBody Dept dept){
        int i=deptService.addDept(dept);
        HashMap<String, Object> map = new HashMap<>();
        if(i>0){
            map.put("status",20000);
            map.put("msg","新增成功!!!");
        }else {
            map.put("status",30000);
            map.put("msg","新增失败！！！");
        }
        return map;
    }





    //删除一个部门
    @DeleteMapping("/deleteDept/{deptId}")
    @ResponseBody
    public HashMap<String,Object> removeDept(@PathVariable Integer deptId){
        Dept dept=deptService.getDept(deptId);
        HashMap<String, Object> hashMap = new HashMap<>();
        if(dept==null){
            hashMap.put("msg","删除失败，该部门不存在");
            hashMap.put("status",30000);
            return hashMap;
        }
        //0代表可用，-1代表冻结，1代表已删除
        dept.setDeptState(1);
        dept.setUpdateTime(new Date());
        int i=deptService.updateDept(dept);

        if(i>0){
            hashMap.put("status",20000);
            hashMap.put("msg","删除成功");
        }else {
            hashMap.put("status",30000);
            hashMap.put("msg","删除失败");
        }
        return hashMap;
    }





    //以下两个方法为更新
    //查询更新部门的信息（判断是否存在）
    @GetMapping("/updateDept/{deptId}")
    public Dept getDeptById(@PathVariable Integer deptId){
        Dept dept = deptService.getDept(deptId);
        return dept;
    }

    //真正更新部门的操作
    @PutMapping("/updateDept")
    @ResponseBody
    public HashMap<String,Object> updateDept(@RequestBody Dept dept){
        int i = deptService.updateDept(dept);
        HashMap<String, Object> hashMap = new HashMap<>();
        if (i>0){
            hashMap.put("status",20000);
            hashMap.put("msg","修改成功");
        }else {
            hashMap.put("status",1204);
            hashMap.put("msg","修改失败");
        }
        return hashMap;
    }


}
